<?php
namespace app\common\model;
use think\model\concern\SoftDelete;
class Account extends \think\Model
{
    protected $resultSetType = 'collection';
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    //所属上级
    public function higher()
    {
        return $this->hasOne('record','b_id','id');
    }

    //所属分销总
    public function distributeInfo(){
        return $this->hasOne('account','id','distribute');
    }

    //所有下级
    public function lower(){
        return $this->hasMany('record','a_id','id');
    }

    //当前角色名
    public function roleInfo(){
        return $this->hasOne('role','id','role');
    }

    //所属楼盘
    public function buildingInfo(){
        return $this -> hasOne('building','id','project')->field('id,name');
    }

    //点位
    public function pointInfo(){
        return $this -> hasOne('buildingPoint','role','role');
    }

    //添加账号客户信息
    public function inserts($loginInfo){
        $data = input('param.');
        $validate = validate($this -> name);
        if(!$validate->check($data))
            return [
                'message' => $validate->getError()
            ];
        //开创全民账号需要验证码
        if ($data['role'] == '33'){
//            if (!$data['code'])
//                return [
//                    'message' => '验证码不能为空'
//                ];
//            $check = $this -> checkSend($data['telephone'],$data['code'],'wholeMan');
//            if ($check !== true)
//                return $check;
            $data['fun'] = '2,3,4,6,7';
        }

        if (!$data['project']){
            $project = $this -> where('id','eq',$loginInfo['id']) ->find()->toArray();
            if($project['project'])
                $data['project'] = $project['project'];
        }

        $savedata['name'] = $data['name'];
        $savedata['telephone'] = $data['telephone'];
        $savedata['role'] = $data['role'];
        $savedata['project'] = $data['project']?:0;
        $savedata['company'] = $data['company'];
        $savedata['distribute'] = $data['distribute'];
        $savedata['style'] = $data['style'];

        $savedata['fun'] = $data['fun'];
        if($data['id']){
            //更新该账号
            $this -> where('id','eq',$data['id']) -> update($savedata);
            return [
                'code' => '1',
                'message' => '更新成功',
                'id' => $data['id'],
            ];
        }else{
            //创建该账号
            $savedata['time'] = time();
            $userInfo = $this -> create($savedata);
            //定义从属关系
            $addData['a_id'] = $loginInfo['id'];
            $addData['b_id'] = $userInfo -> id;
            \app\common\model\Record::create($addData);
            return [
                'code' => '1',
                'message' => '新增成功',
                'id' => $userInfo -> id
            ];
        }
    }

    //删除当前账户信息
    public function dels(){
        $data = input('param.');
        \app\common\model\Account::destroy($data['id']);
        $record_id = \app\common\model\Record::where('b_id','eq',$data['id']) -> find();
        \app\common\model\Record::destroy($record_id['id']);
        return [
            'code' => '1',
            'message' => '删除成功',
        ];
    }

    /**
     * 发送登陆短信
     * @param  string  $telephone  接受短信手机号
     * @return string  $token      加密后的验证码
     */
    public function send(){
        $telephone = input('param.telephone');
        $send = new \app\common\logic\Send();
        return $send -> code($telephone,mt_rand(100000,999999),'admin');
    }

    /**
     * 验证登陆
     * @param  string  $data['telephone']  用户填写的手机号
     * @param  string  $data['code']       用户填写的验证码
     * @return string  $token
     */
    public function login(){
        $data = input('param.');
        //检查验证码
        $check = $this -> checkSend($data['telephone'],$data['code'],'admin');
        if ($check !== true)
            return $check;
        $info = $this -> where('telephone',$data['telephone'])->find();
        if (!$info)
            return ['message'=> '该账号不存在'];
        $token = dataSign([
            'telephone' => $info['telephone'],
            'date' => time()
        ]);
        //存入缓存
        cache($token,[
            'auth' => 'admin',
            'telephone' => $info['telephone'],
            'time' => time()
        ],3600*24*365);
        return [
            'code' => '1',
            'message' => '登陆成功',
            'token' => $token,
        ];
    }

    /**
     * 验证登陆短信
     * @param  string  $telephone  用户填写的手机号
     * @param  string  $code       用户填写的验证码
     * @param  string  $auth       验证类型
     * @return bool
     */
    private function checkSend($telephone='',$code ='',$auth){
        $checkTel = checkTel($telephone);
        if($checkTel !== true)
            return $checkTel;

        if (!$code)
            return [
                'message' => '验证码不能为空'
            ];
        $cacheTel = cache($telephone.$auth);

        if (!$cacheTel)
            return [
                'message' => '验证码不正确'
            ];
        if ($cacheTel['num'] >=5)
            return [
                'message' => '验证次数过多，请一小时后再试'
            ];

        if ($code == $cacheTel['code']){
            cache($telephone.$auth,null);
            return true;
        }


        $cacheTel['num'] +=1;
        cache($telephone.$auth,$cacheTel,3600);
        return [
            'message' => '验证码不正确'
        ];
    }

    /**
     * 注销登陆
     * @param  string  $token  用户token
     * @return bool
     */
    public function logout(){
        cache(input('token'),null);
        return [
            'code' => '1',
            'message' => '注销成功'
        ];
    }
}